package com.airS.task.fileMgr.common.query;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by alan on 2017/3/9.
 */
public class PageQuery<T extends PageQuery> {

    /**
     * 默认起始页
     */
    public static final int DEFAULT_PAGE_NUM = 1;
    /**
     * 默认分页大小
     */
    public static final int DEFAULT_PAGE_SIZE = 12;
    /**
     * 防止误传入过大分页数 影响性能
     */
    private static final int MAX_PAGE_SIZE = 1000;
    /**
     * 当前页
     */
    private Integer pageNum;
    /**
     * 每页的数量
     */
    private Integer pageSize;
    /**
     * 请求路径
     */
    private String requestUrl;

    public Integer getPageNum() {
        if (pageNum == null)
            pageNum = DEFAULT_PAGE_NUM;
        else if (pageNum > MAX_PAGE_SIZE)
            return MAX_PAGE_SIZE;
        return pageNum;
    }

    public T setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
        return (T) this;
    }

    public Integer getPageSize() {
        if (pageSize == null)
            pageSize = DEFAULT_PAGE_SIZE;
        return pageSize;
    }

    public T setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
        return (T) this;
    }

    public String getRequestUrl() {
        return requestUrl;
    }

    public T setRequestUrl(String requestUrl) {
        int i = requestUrl.indexOf("?");
        if (i > -1) {
            StringBuffer paramstr = new StringBuffer();
            List<String> params = Arrays.asList(requestUrl.substring(i + 1).split("&"));
            for (Iterator<String> iterator = params.iterator(); iterator.hasNext(); ) {
                String param = iterator.next();
                if (!param.startsWith("pageNum"))
                    paramstr.append("&").append(param);
            }
            if (paramstr.length() > 0)
                paramstr.deleteCharAt(0);

            requestUrl = requestUrl.substring(0, i + 1) + paramstr.toString();
        }
        this.requestUrl = requestUrl;
        return (T) this;
    }

}
